package com.letao.service.impl;

import com.letao.common.pojo.EasyUITreeNode;
import com.letao.common.pojo.LetaoResult;
import com.letao.mapper.TbContentCategoryMapper;
import com.letao.pojo.TbContentCategory;
import com.letao.pojo.TbContentCategoryExample;
import com.letao.service.ContentCategrayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ac on 2017/1/18.
 */
@Service
public class ContentCategrayServiceImpl implements ContentCategrayService {

    @Autowired
    private TbContentCategoryMapper tbContentCategoryMapper;

    @Override
    public List<EasyUITreeNode> getContentCategray(Long parentId) {
        TbContentCategoryExample example = new TbContentCategoryExample();
        example.createCriteria().andParentIdEqualTo(parentId);
        List<TbContentCategory> list = tbContentCategoryMapper.selectByExample(example);
        List<EasyUITreeNode> easyUITreeNodes = new ArrayList<>();
        for (TbContentCategory category :
                list) {
            if (category.getIsParent()) {
                easyUITreeNodes.add(new EasyUITreeNode(category.getId(), category.getName(), "closed"));
            } else {
                easyUITreeNodes.add(new EasyUITreeNode(category.getId(), category.getName(), "open"));
            }
        }
        return easyUITreeNodes;
    }

    @Override
    public LetaoResult insertContetCategory(String name, Long parentId) {
        TbContentCategory category = new TbContentCategory();
        category.setName(name);
        category.setParentId(parentId);
        category.setIsParent(false);
        category.setUpdated(new Date());
        category.setStatus(1);
        category.setSortOrder(1);
        category.setCreated(new Date());
        int insert = tbContentCategoryMapper.insert(category);
        //查看父节点的isparent列是否为true,如果不是true该为true
        TbContentCategory tbContentCategory = tbContentCategoryMapper.selectByPrimaryKey(parentId);
        if (!tbContentCategory.getIsParent()){
            tbContentCategory.setIsParent(true);
            tbContentCategoryMapper.updateByPrimaryKey(tbContentCategory);
        }
        return LetaoResult.ok(category);
    }

    @Override
    public LetaoResult upadteContentCategory(String name, Long id) {
        TbContentCategory category = new TbContentCategory();
        category.setId(id);
        category.setName(name);
        tbContentCategoryMapper.updateByPrimaryKeySelective(category);
        return LetaoResult.ok();
    }

    @Override
    public LetaoResult deleteCcontentCategory(Long id) {
        tbContentCategoryMapper.deleteByPrimaryKey(id);
        TbContentCategoryExample example = new TbContentCategoryExample();
        example.createCriteria().andParentIdEqualTo(id);
        tbContentCategoryMapper.deleteByExample(example);
        return LetaoResult.ok();
    }

}
